#coding=utf-8
'''
@author Ivehui
@time 2016/06/05
@function save tuple data
'''


import numpy as np
import parameters as pms
import random


class Storage(object):
    def __init__(self, max_size=10000):
        self.size = 0
        self.max_size = int(max_size)
        self.isFull = False

        self.state = np.zeros((max_size, pms.stateSize))
        self.action=np.zeros((max_size,pms.actionSize))
        self.reward = np.zeros((max_size, 1))
        self.done = np.zeros((max_size, 1))

        self.s_t_data = np.zeros([pms.batchSize, pms.stateSize], dtype="float32")
        self.s_t_plus_1_data = np.zeros([pms.batchSize, pms.stateSize], dtype="float32")
        self.action_data = np.zeros([pms.batchSize, pms.actionSize], dtype="float32")
        self.reward_data = np.zeros([pms.batchSize, 1], dtype="float32")
        self.done_data = np.zeros([pms.batchSize, 1], dtype="float32")
    def sample(self):
        all_selected_items=[]
        for index in range(0,pms.batchSize):
            while(True):
                selected=random.randint(0,self.getBufferSize()-1)
                # if(self.done[selected]==0):# 应该可以使用done掉的数据，因为计算target时，done掉的数据其实与下一帧无关
                #     continue
                if(selected==self.getSize()-1):#减1是因为self.size一直指向下一个可写位置
                    continue
                if selected in all_selected_items:
                    continue
                break
            all_selected_items.append(selected)
            self.s_t_plus_1_data[index] = self.state[(selected+1)%self.getBufferSize()]
            self.s_t_data[index] = self.state[selected]
            self.action_data[index] = self.action[selected]
            self.reward_data[index] = self.reward[selected]
            self.done_data[index] = self.done[selected]
        return self.s_t_data,self.action_data,self.s_t_plus_1_data,self.done_data,self.reward_data
    def saveTuple(self, state, actionNum, reward, done):
        action = np.zeros(pms.actionSize)
        action[actionNum] = 1
        if self.size < self.max_size:
            self.state[self.size] = state
            self.action[self.size] = action
            self.reward[self.size] = reward
            self.done[self.size] = 0 if done else 1
            self.size += 1
        else:
            self.state[0] = state
            self.action[0] = action
            self.reward[0] = reward
            self.done[0] = 0 if done else 1
            self.isFull = True
            self.size = 1

    def getBufferSize(self):# 得到的是buffer被占据的情况
        if self.isFull:
            return self.max_size
        else:
            return self.size

    def getSize(self):#得到的是当前的指针
        return self.size

    def getIsFull(self):
        return self.isFull

    def getCurActionHistory(self):
        return self.curActionHistory
